import json
import os
import re


def read_results_json(file_path):
    with open(file_path, 'r') as f:
        data = json.load(f)
    return set(data.keys())


def extract_component_name_and_subsystem(file_path):
    component_regex = re.compile(
        r'"component"\s*:\s*\{\s*"name"\s*:\s*"([^"]+)"\s*,\s*"subsystem"\s*:\s*"([^"]+)"'
    )

    with open(file_path, 'r') as f:
        content = f.read()

    match = component_regex.search(content)

    if match:
        return match.group(1), match.group(2)
    else:
        return None, None


# 在指定目录中查找所有bundle.json文件，并匹配component里的name和subsystem
def find_and_match_bundle_json(search_directory, keys):
    matches = {}  # 使用字典来存储匹配结果，subsystem为键，name列表为值
    for root, _, files in os.walk(search_directory):
        for file in files:
            if file == 'bundle.json':
                file_path = os.path.join(root, file)
                name, subsystem = extract_component_name_and_subsystem(file_path)
                if name and name in keys:
                    if subsystem not in matches:
                        matches[subsystem] = []
                    matches[subsystem].append(name)
    return matches


def main():
    results_file = 'results.json'
    search_directory = '/home/user/OH/openHarmonyMaster'
    output_file = 'subsystem.json'

    keys = read_results_json(results_file)

    # 查找并匹配bundle.json文件中component里的name和subsystem
    matches = find_and_match_bundle_json(search_directory, keys)

    with open(output_file, 'w') as f:
        json.dump(matches, f, indent=4)

    print(f'Matched results have been written to {output_file}')


if __name__ == '__main__':
    main()